import { Button, message, Popconfirm, Select, Space, Table, Tag, type TablePaginationConfig, type TableProps } from "antd";
import { useCallback, useEffect, useState, type JSX } from "react";
import { authFetch, ROLE_API } from "../utils/api";
import { format } from "date-fns";
import type { Role, SelectRole } from "../utils/role";
import RoleEditModal from "../components/RoleEditModal";

export default function RoleManage(): JSX.Element {
    // 查询相关参数
    const [role, setRole] = useState<string>();
    const [status, setStatus] = useState<number>();
    const [isSystem, setIsSystem] = useState<number>();
    // 搜索框初始化
    const [roles, setRoles] = useState<SelectRole[]>([]);

    // 表格相关参数
    const [tableData, setTableData] = useState<Role[]>([]);
    const [pagination, setPagination] = useState<TablePaginationConfig>({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    // 组件状态
    const [loading, setLoading] = useState(false);

    // 编辑组件状态
    const [editModalVisible, setEditModalVisible] = useState(false);
    const [editRole, setEditRole] = useState<Role | undefined>(undefined)
    const [editModalLoading, setEditModalLoading] = useState(false);



    // 初始化组件
    useEffect(() => {
        // 初始化角色下拉列表
        fetchRoleList()
        // 初始化表格
        pageFetchRoles();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    // 查询所有角色列表方法
    const fetchRoleList = useCallback(
        async () => {
            setLoading(true);
            try {
                const res = await authFetch(ROLE_API.ALL, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })

                if (res.ok) {
                    // 处理响应数据
                    const roleList = (await res.json())?.data?.map((item: { code: string; name: string; }) => {
                        return {
                            value: item.code,
                            label: item.name + '_' + item.code
                        }
                    })
                    setRoles(roleList || [])
                } else {
                    throw new Error('全部角色列表请求失败');
                }
            } catch (error) {
                console.log(error);
                message.error('全部角色列表请求失败');
            } finally {
                setLoading(false);
            }
        }, []
    )

    // 分页查询角色列表方法
    const pageFetchRoles = useCallback(
        async (page = 1, pageSize = 10, code?: string, status?: number, isSystem?: number) => {
            setLoading(true);
            try {
                const query = {
                    current: page,
                    pageSize: pageSize,
                    code: code,
                    status: status,
                    isSystem: isSystem,
                }

                const res = await authFetch(ROLE_API.PAGE, {
                    method: 'POST',
                    body: JSON.stringify(query),
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })

                if (!res.ok) {
                    throw new Error(`HTTP ${res.status}`);
                }

                const data = (await res.json())?.data;

                // 设置角色列表数据
                setTableData(data?.records || [])
                // 设置分页信息
                setPagination({
                    current: data!.current,
                    pageSize: data!.pageSize,
                    total: data!.total,
                })
            } catch (error) {
                console.log(error);
                message.error('角色列表请求失败');
            } finally {
                setLoading(false);
            }
        }, []
    )

    // 操作方法
    async function handleDelete(id: number) {
        const res = await authFetch(ROLE_API.DELETE(id), {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        })

        if (!res.ok) {
            throw new Error(`HTTP ${res.status}`);
        } else {
            console.log(`HTTP ${res.status}`)
        }

        // 刷新页面
        pageFetchRoles(pagination.current, pagination.pageSize, role, status, isSystem)
    }

    async function handleRecover(id: number) {
        const res = await authFetch(ROLE_API.RECOVER(id), {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            }
        })

        if (!res.ok) {
            throw new Error(`HTTP ${res.status}`);
        }

        // 刷新页面
        pageFetchRoles(pagination.current, pagination.pageSize, role, status, isSystem)
    }

    function handleSearch() {
        pageFetchRoles(1, pagination.pageSize, role, status, isSystem)
    }

    function handleTableChange(pagination: TablePaginationConfig) {
        pageFetchRoles(pagination.current, pagination.pageSize, role, status, isSystem)
        setPagination(pagination)
    }

    async function handleStatus(record: Role) {
        // 更新角色状态
        record.status = record.status === 1 ? 0 : 1;
        const res = await authFetch(ROLE_API.UPDATE, {
            method: 'POST',
            body: JSON.stringify(record),
            headers: {
                'Content-Type': 'application/json',
            }
        })

        if (!res.ok) {
            throw new Error(`HTTP ${res.status}`);
        }

        // 刷新页面
        pageFetchRoles(pagination.current, pagination.pageSize, role, status, isSystem)
    }

    // 编辑组件方法
    async function handleEditModalSave(record: Role) {
        try {
            setEditModalLoading(true);
            // 根据id是否存在决定是新增还是更新
            const url = record.id === undefined ? ROLE_API.CREATE : ROLE_API.UPDATE;
            const res = await authFetch(url, {
                method: 'POST',
                body: JSON.stringify(record),
                headers: {
                    'Content-Type': 'application/json',
                }
            })

            if (!res.ok) {
                throw new Error(`HTTP ${res.status}`);
            }

            // 刷新页面
            pageFetchRoles(pagination.current, pagination.pageSize, role, status, isSystem)
            // 关闭编辑组件，清除表单数据
            setEditModalVisible(false)
            setEditRole(undefined)
        } catch (error) {
            console.log(error);
            message.error('角色保存失败');
        } finally {
            setEditModalLoading(false);
        }
    }

    function handleEditModalClose() {
        // 关闭编辑组件，清除表单数据
        setEditModalVisible(false)
        setEditRole(undefined)
    }

    function openEditModal(id: number) {
        const record = tableData.find(item => item.id === id);
        if (record) {
            setEditRole(record);
            setEditModalVisible(true);
        }
    }

    const columns: TableProps<Role>['columns'] = [
        {
            title: "ID",
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '角色编码',
            dataIndex: 'code',
            key: 'code',
            fixed: "left",
        },
        {
            title: '角色名称',
            dataIndex: 'name',
            key: 'name',
            fixed: "left",
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status: number) => {
                return status === 1 ?
                    <Tag color='green' key='启用'>启用</Tag>
                    : <Tag color='red' key='启用'>禁用</Tag>
            }
        },
        {
            title: '是否内置',
            dataIndex: 'isSystem',
            key: 'isSystem',
            render: (text) => {
                return <Tag color={text === 1 ? 'geekblue' : 'orange'} >{text === 1 ? '是' : '否'}</Tag>
            }
        },
        {
            title: '排序',
            dataIndex: 'sort',
            key: 'sort'
        },
        {
            title: '创建者',
            dataIndex: 'createBy',
            key: 'createBy'
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (_, record) => {
                return format(new Date(record.createTime), 'yyyy-MM-dd HH:mm:ss');
            }
        },
        {
            title: '更新者',
            dataIndex: 'updateBy',
            key: 'updateBy'
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render: (_, record) => {
                return format(new Date(record.updateTime), 'yyyy-MM-dd HH:mm:ss');
            }
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            render: (_, record) => {
                return <Space size="middle">
                    <Button type="primary" size="small" disabled={record.deleted} onClick={ () => openEditModal(record.id) }>
                        编辑
                    </Button>
                    {
                        record.status ?
                            <Button disabled={record.deleted} onClick={() => handleStatus(record)} color="danger" variant="solid" size="small" >禁用</Button>
                            :
                            <Button disabled={record.deleted} onClick={() => handleStatus(record)} color="green" variant="solid" size="small" > 启用</Button >
                    }
                    {
                        !record.deleted ?
                            <Popconfirm title="确定要删除该角色吗？" onConfirm={() => handleDelete(record.id)} okText="是" cancelText="否">
                                <Button size="small"  color="danger" variant="solid">删除</Button>
                            </Popconfirm>
                            :
                            <Popconfirm title="确定要恢复该角色吗？" onConfirm={() => handleRecover(record.id)} okText="是" cancelText="否">
                                <Button size="small"  color="green" variant="solid">恢复</Button>
                            </Popconfirm>
                    }
                </Space >
            }
        }
    ]

    return <div style={{ background: "#fff", padding: 24, borderRadius: 8 }}>
        <Space style={{ marginBottom: 16 }} align="baseline">
            <Space.Compact>
                <span style={{ padding: '0 8px', lineHeight: '32px', background: '#f5f5f5', border: '1px solid #d9d9d9', borderRight: 'none', borderRadius: '6px 0 0 6px', width: 80, textAlign: 'center' }}>角色名称</span>
                <Select
                    placeholder="请选择角色"
                    style={{ width: 240, height: 32, borderRadius: '0 6px 6px 0' }}
                    value={role}
                    onChange={setRole}
                    options={roles}
                    showSearch
                    filterOption={(inputValue, option) => {
                        return (option?.label ?? '').toLowerCase().includes(inputValue.toLowerCase());
                    }}
                    allowClear
                />
            </Space.Compact>
            <Space.Compact>
                <span style={{ padding: '0 8px', lineHeight: '32px', background: '#f5f5f5', border: '1px solid #d9d9d9', borderRight: 'none', borderRadius: '6px 0 0 6px', width: 80, textAlign: 'center' }}>状态</span>
                <Select
                    placeholder="请选择状态"
                    style={{ width: 120, height: 32, borderRadius: '0 6px 6px 0' }}
                    value={status}
                    onChange={setStatus}
                    options={[
                        { value: 1, label: '启用' },
                        { value: 0, label: '禁用' }
                    ]}
                    allowClear
                />
            </Space.Compact>
            <Space.Compact>
                <span style={{ padding: '0 8px', lineHeight: '32px', background: '#f5f5f5', border: '1px solid #d9d9d9', borderRight: 'none', borderRadius: '6px 0 0 6px', width: 80, textAlign: 'center' }}>系统内置</span>
                <Select
                    placeholder="是否系统内置"
                    style={{ width: 130, height: 32, borderRadius: '0 6px 6px 0' }}
                    value={isSystem}
                    onChange={setIsSystem}
                    options={[
                        { value: '1', label: '是' },
                        { value: '0', label: '否' },
                    ]}
                    allowClear
                />
            </Space.Compact>
            <Button type="primary" onClick={handleSearch}>查询</Button>
        </Space>

        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
            <Button
                type="primary"
                onClick={() => {
                    setEditRole(undefined);
                    setEditModalVisible(true);
                }}
            >
                新增角色
            </Button>
        </div>

        {
            editModalVisible &&
            <RoleEditModal
                visible={editModalVisible}
                onCancel={handleEditModalClose}
                onSave={handleEditModalSave}
                role={editRole}
                loading={editModalLoading}
            />
        }

        <Table<Role>
            columns={columns}
            dataSource={tableData}
            loading={loading}
            rowKey="id"
            scroll={{ x: 'max-content' }}
            rowClassName={(_, index) => index % 2 === 0 ? 'even-row' : 'odd-row'}
            onChange={handleTableChange}
            pagination={{
                ...pagination,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条`,
            }}
        />

    </div>

}
